/**************************************************************************(C)*
 *
 *  This file is part of the GreenHills project
 *  Copyright (C) 2009  Tieto Corporation
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  Not for commmercial use. Only with Tieto permission.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *************************************************************************(C)*/

#include <QMutexLocker>
#include <QMetaType>

#include <termios.h>
#include <sys/signal.h>
#include <fcntl.h>
#include <unistd.h>

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>


#include "../serialport.h"

using namespace greenhills::util;

class CSerialPort::Private
{
public:
    Private(CSerialPort *publ);
    virtual ~Private();

friend class CSerialPort;

private:
    static void sigio_handler(int status);

private:
    static QMutex mMutex;
    static int mPortHandle;
    static CSerialPort *mSerialPortInstance;
    struct termios oldtio;
};

QMutex CSerialPort::Private::mMutex;
int CSerialPort::Private::mPortHandle = -1;
CSerialPort *CSerialPort::Private::mSerialPortInstance = 0;

//==============================================================================
// Private part
//==============================================================================
CSerialPort::Private::Private(CSerialPort *publ)
    //:mPublic(*publ)
{    
    mSerialPortInstance = publ;
}

CSerialPort::Private::~Private()
{
}
//see...
//http://publib.boulder.ibm.com/infocenter/zos/v1r9/index.jsp?topic=/com.ibm.zos.r9.bpxbd00/s119mi.htm
//SA_SIGINFO
//void func(int signo, siginfo_t *info, void *context);
void CSerialPort::Private::sigio_handler(int status)
{
    Q_UNUSED(status);
    if (status==29)
    {
        char buf[256];
        int res = 0;
        {
            //QMutexLocker locker(&mMutex);
            res = read(mPortHandle,buf,255);
        }
        if (res>0)
        {
            buf[res]=0;
            QByteArray ba(buf, res);
            //std::cout << "Data: " << buf << std::endl;
            Q_EMIT( mSerialPortInstance->dataReceived(ba) );
        }
    }
    else
    {
        std::cout << "sigio_handler: status = " << status << std::endl;
    }
}


//==============================================================================
// Public part
//==============================================================================
CSerialPort *CSerialPort::instance()
{
    static CSerialPort *serialPortInstance = new CSerialPort();
    return serialPortInstance;
}

CSerialPort::CSerialPort()
    :QThread(),mPrivate(*new Private(this))
{
    //qRegisterMetaType<QByteArray>("QByteArray");
    moveToThread(this);
}

CSerialPort::~CSerialPort()
{
    delete &mPrivate;
}

bool CSerialPort::open(const char *device, int baudrate)
{
    QMutexLocker locker(&mPrivate.mMutex);
    if (mPrivate.mPortHandle >= 0)
        return false;

    mPrivate.mPortHandle = ::open(device, O_RDWR | O_NOCTTY | O_NONBLOCK);
    if (mPrivate.mPortHandle <0)
        return false;

    struct sigaction saio;
    saio.sa_handler = &CSerialPort::Private::sigio_handler;
    sigemptyset(&saio.sa_mask);
    saio.sa_flags = 0;
    saio.sa_flags = SA_NODEFER;
    saio.sa_restorer = NULL;
    sigaction(SIGIO,&saio,NULL);

    fcntl(mPrivate.mPortHandle, F_SETOWN, getpid());
    fcntl(mPrivate.mPortHandle, F_SETFL, FASYNC);
    tcgetattr(mPrivate.mPortHandle,&mPrivate.oldtio);

    if (baudrate != 0)
    {
        struct termios newtio;
        memset(&newtio, 0, sizeof(newtio));

        newtio.c_cflag = baudrate | CRTSCTS | CS8 | CLOCAL | CREAD;
        newtio.c_iflag = IGNPAR ;
        tcflush(mPrivate.mPortHandle, TCIFLUSH);
        tcsetattr(mPrivate.mPortHandle, TCSANOW, &newtio);
    }

    start();
    return true;
}

void CSerialPort::run()
{
    QThread::run();
}

bool CSerialPort::close()
{
    terminate();
    wait(1000);

    QMutexLocker locker(&mPrivate.mMutex);

    if (mPrivate.mPortHandle < 0)
        return false;


    tcsetattr(mPrivate.mPortHandle,TCSANOW,&mPrivate.oldtio);

    if (::close(mPrivate.mPortHandle) < 0)
        return false;

    mPrivate.mPortHandle = -1;
    return true;
}
